<template>
  <div class="self-service-point-management">
    <div class="page-header">
      <h2 class="page-title">自助点管理</h2>
      <el-button type="primary" @click="showAddDialog" :disabled="loading" icon="el-icon-plus">
        新增自助点
      </el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="always">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
        <el-form-item label="名称">
          <el-input
              v-model="searchForm.name"
              placeholder="请输入名称"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isActive" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading" icon="el-icon-search">
            搜索
          </el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 自助点列表 -->
    <el-card class="table-card" shadow="always">
      <el-table
          :data="paginatedData"
          style="width: 100%; height: 600px"
      border
      v-loading="loading"
      :default-sort="{ prop: 'pointId', order: 'descending' }"
      empty-text="暂无自助点数据"
      class="custom-table"
      key="mainTable"
      >
        <el-table-column prop="pointId" label="ID" width="80" sortable align="center" />
        <el-table-column prop="name" label="名称" sortable min-width="150" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="contactNumber" label="联系电话" width="130" />
        <el-table-column prop="isActive" label="状态" width="100" sortable align="center">
          <template #default="scope">
            <el-tag
                :type="scope.row.isActive ? 'success' : 'danger'"
                effect="dark"
                size="small"
            >
              {{ scope.row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="adminId" label="管理员ID" width="100" v-if="isSuperAdmin" align="center" />
        <el-table-column prop="deviceCount" label="设备数量" width="100" sortable align="center" />
        <el-table-column prop="poster" label="海报" width="150" align="center">
          <template #default="scope">
            <el-image
                v-if="scope.row.poster"
                :src="scope.row.poster"
                style="width: 80px; height: 80px"
                fit="cover"
                :preview-src-list="[scope.row.poster]"
                lazy
                class="poster-image"
            />
            <span v-else class="no-image">暂无海报</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="showEditDialog(scope.row)"
                icon="el-icon-edit"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="deletePoint(scope.row.pointId)"
                icon="el-icon-delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="800px"
        :close-on-click-modal="false"
        custom-class="custom-dialog"
        @opened="handleDialogOpened"
        @closed="handleDialogClosed"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="dialog-form">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
              v-model="form.address"
              placeholder="请输入地址或在地图上选择"
              @input="searchAddress"
          />
        </el-form-item>
        <el-form-item label="地图位置">
          <MapContainer
              v-if="mapVisible"
              ref="editMap"
              style="width: 100%; height: 300px;"
              :center="[form.longitude || 116.397428, form.latitude || 39.90923]"
              @update-position="updatePosition"
              @location-fetched="locationFetched"
          />
          <el-button type="primary" size="small" @click="getCurrentLocation" style="margin-top: 10px">
            获取当前位置
          </el-button>
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model.number="form.latitude" type="number" step="0.000001" placeholder="地图自动填充" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model.number="form.longitude" type="number" step="0.000001" placeholder="地图自动填充" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch
              v-model="form.isActive"
              active-text="启用"
              inactive-text="禁用"
              active-color="#13ce66"
              inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="管理员ID" prop="adminId" v-if="isSuperAdmin">
          <el-input v-model.number="form.adminId" type="number" placeholder="请输入管理员ID" />
        </el-form-item>
        <el-form-item label="海报" prop="poster">
          <el-upload
              action=""
              :http-request="handlePosterUpload"
              :show-file-list="false"
              accept="image/*"
              :before-upload="beforeUpload"
              class="poster-upload"
          >
            <el-button type="primary" size="small">点击上传</el-button>
            <div v-if="form.poster" class="poster-preview">
              <el-image :src="form.poster" style="width: 120px; height: 120px" fit="cover" />
              <el-button type="danger" size="small" @click.stop="removePoster" class="remove-btn">
                移除
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" :disabled="submitting">取消</el-button>
        <el-button
            type="primary"
            @click="submitForm"
            :loading="submitting"
            icon="el-icon-check"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed, nextTick, onBeforeUnmount } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import _ from 'lodash';
import MapContainer from '../components/MapContainer.vue';

// 表格相关数据和逻辑
const selfServicePoints = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const loading = ref(false);
const submitting = ref(false);
const mapVisible = ref(false); // 控制 MapContainer 的渲染
const searchForm = reactive({
  name: '',
  isActive: null,
});
const currentPage = ref(1);
const pageSize = ref(10);

const form = reactive({
  pointId: null,
  name: '',
  address: '',
  contactNumber: '',
  isActive: true,
  adminId: null,
  latitude: null,
  longitude: null,
  poster: null,
  posterFile: null,
});

const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在 5 到 100 个字符', trigger: 'blur' },
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
  ],
  adminId: [
    { type: 'number', message: '管理员ID必须为数字', trigger: 'blur' },
    {
      required: true,
      message: '请输入管理员ID',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (isSuperAdmin.value && !value) callback(new Error('请输入管理员ID'));
        else callback();
      },
    },
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' },
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' },
  ],
};

const store = useStore();
const router = useRouter();
const editMap = ref(null);

const adminInfo = computed(() => store.state.adminInfo || { username: '管理员', role: '' });
const isSuperAdmin = computed(() => adminInfo.value.role === 'super');

const filteredData = computed(() => {
  return selfServicePoints.value.filter((point) => {
    const nameMatch = searchForm.name
        ? point.name.toLowerCase().includes(searchForm.name.toLowerCase())
        : true;
    const statusMatch =
        searchForm.isActive !== null ? point.isActive === searchForm.isActive : true;
    return nameMatch && statusMatch;
  });
});

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

const formRef = ref(null);

onMounted(() => {
  fetchSelfServicePoints();
});

const fetchSelfServicePoints = _.debounce(async () => {
  try {
    loading.value = true;
    const token = sessionStorage.getItem('token');
    if (!token) {
      ElMessage.error('未登录，请先登录');
      router.push('/login');
      return;
    }

    const response = await axios.get('/api/self-service-points', {
      headers: {
        Authorization: `Bearer ${token}`,
        Role: adminInfo.value.role || '',
        Username: encodeURIComponent(adminInfo.value.username || ''),
      },
    });

    selfServicePoints.value = response.data || [];
    if (selfServicePoints.value.length === 0) {
      ElMessage.info('暂无自助点数据');
    }
    console.log(
        `Fetching self-service points for role: ${adminInfo.value.role}, username: ${adminInfo.value.username}`
    );
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取自助点列表失败';
    ElMessage.error(errorMsg);
    console.error(
        `Failed to fetch self-service points for role: ${adminInfo.value.role}, username: ${adminInfo.value.username}`,
        error
    );
  } finally {
    loading.value = false;
  }
}, 300);

const handleSearch = () => {
  currentPage.value = 1;
  fetchSelfServicePoints();
};

const resetSearch = () => {
  searchForm.name = '';
  searchForm.isActive = null;
  currentPage.value = 1;
  fetchSelfServicePoints();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const showAddDialog = () => {
  dialogTitle.value = '新增自助点';
  Object.assign(form, {
    pointId: null,
    name: '',
    address: '',
    contactNumber: '',
    isActive: true,
    adminId: null,
    latitude: null,
    longitude: null,
    poster: null,
    posterFile: null,
  });
  openDialog();
};

const showEditDialog = (row) => {
  dialogTitle.value = '编辑自助点';
  Object.assign(form, { ...row, posterFile: null });
  openDialog();
};

const openDialog = _.debounce(() => {
  dialogVisible.value = true;
  nextTick(() => {
    formRef.value?.clearValidate();
  });
}, 200); // 防抖 200ms

const handleDialogOpened = () => {
  mapVisible.value = true; // 对话框打开后渲染地图
};

const handleDialogClosed = () => {
  mapVisible.value = false; // 对话框关闭时隐藏地图
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) ElMessage.error('只能上传图片文件');
  if (!isLt2M) ElMessage.error('图片大小不能超过 2MB');
  return isImage && isLt2M;
};

const handlePosterUpload = (params) => {
  form.posterFile = params.file;
  form.poster = URL.createObjectURL(params.file);
};

const removePoster = () => {
  form.poster = null;
  form.posterFile = null;
};

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;

    submitting.value = true;
    try {
      const token = sessionStorage.getItem('token');
      if (!token) {
        ElMessage.error('未登录，请先登录');
        router.push('/login');
        return;
      }

      const formData = new FormData();
      const dto = {
        name: form.name,
        address: form.address,
        contactNumber: form.contactNumber,
        active: form.isActive,
        latitude: form.latitude,
        longitude: form.longitude,
      };

      if (isSuperAdmin.value && form.adminId !== null) {
        dto.adminId = form.adminId;
      }

      formData.append('dto', new Blob([JSON.stringify(dto)], { type: 'application/json' }));
      if (form.posterFile) {
        formData.append('poster', form.posterFile);
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'multipart/form-data',
          Role: adminInfo.value.role || '',
          Username: encodeURIComponent(adminInfo.value.username || ''),
        },
      };

      if (form.pointId) {
        await axios.put(`/api/self-service-points/${form.pointId}`, formData, config);
        ElMessage.success('自助点更新成功');
        console.log(
            `Successfully updated self-service point ${form.pointId} for username: ${adminInfo.value.username}`
        );
      } else {
        await axios.post('/api/self-service-points', formData, config);
        ElMessage.success('自助点添加成功');
        console.log(`Successfully created self-service point for username: ${adminInfo.value.username}`);
      }

      dialogVisible.value = false;
      fetchSelfServicePoints();
    } catch (error) {
      const errorMsg = error.response?.data?.message || '操作失败';
      ElMessage.error(errorMsg);
      console.error(
          `Failed to ${form.pointId ? 'update' : 'create'} self-service point for role: ${adminInfo.value.role}, username: ${adminInfo.value.username}`,
          error
      );
    } finally {
      submitting.value = false;
    }
  });
};

const deletePoint = (pointId) => {
  ElMessageBox.confirm('确定删除此自助点吗？此操作不可撤销', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        try {
          const token = sessionStorage.getItem('token');
          if (!token) {
            ElMessage.error('未登录，请先登录');
            router.push('/login');
            return;
          }

          await axios.delete(`/api/self-service-points/${pointId}`, {
            headers: {
              Authorization: `Bearer ${token}`,
              Role: adminInfo.value.role || '',
              Username: encodeURIComponent(adminInfo.value.username || ''),
            },
          });

          ElMessage.success('自助点删除成功');
          console.log(
              `Successfully deleted self-service point ${pointId} for username: ${adminInfo.value.username}`
          );
          fetchSelfServicePoints();
        } catch (error) {
          const errorMsg = error.response?.data?.message || '删除失败';
          ElMessage.error(errorMsg);
          console.error(
              `Failed to delete self-service point ${pointId} for role: ${adminInfo.value.role}, username: ${adminInfo.value.username}`,
              error
          );
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

// 地图相关方法，使用 MapContainer 的 ref 调用
const getCurrentLocation = () => {
  if (editMap.value) {
    editMap.value.getCurrentLocation();
  }
};

const searchAddress = _.debounce((value) => {
  if (!value || !editMap.value) return;
  editMap.value.searchAddress(value);
}, 300);

const updatePosition = ({ lng, lat }) => {
  form.longitude = lng;
  form.latitude = lat;
  if (editMap.value) {
    editMap.value.getAddress([lng, lat], (address) => {
      form.address = address;
    });
  }
};

const locationFetched = (lnglat) => {
  form.longitude = lnglat[0];
  form.latitude = lnglat[1];
  if (editMap.value) {
    editMap.value.getAddress(lnglat, (address) => {
      form.address = address;
    });
  }
};

const handleGlobalError = (event) => {
  if (event.message && event.message.includes('ResizeObserver loop completed')) {
    event.preventDefault();
    event.stopImmediatePropagation();
    return false;
  }
};onMounted(() => {
  window.addEventListener('error', handleGlobalError);
  fetchSelfServicePoints();
});

onBeforeUnmount(() => {
  window.removeEventListener('error', handleGlobalError);
});

</script>

<style scoped>
.self-service-point-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  background: #fff;
}

.search-form {
  padding: 10px 0;
}

.table-card {
  border-radius: 8px;
  background: #fff;
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header-wrapper th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.poster-image {
  border-radius: 4px;
  transition: transform 0.3s;
}

.poster-image:hover {
  transform: scale(1.05);
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.pagination-container {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
}

.custom-dialog {
  border-radius: 8px;
}

.dialog-form {
  padding: 0 20px;
}

.poster-upload {
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  gap: 10px;
}

.poster-preview {
  margin-top: 10px;
  position: relative;
  display: inline-block;
}

.poster-preview .el-image {
  border-radius: 4px;
}

.remove-btn {
  position: absolute;
  bottom: 5px;
  right: 5px;
}

.el-button {
  border-radius: 6px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-button[type="primary"] {
  background: #409eff;
  border-color: #409eff;
}

.el-button[type="danger"] {
  background: #f56c6c;
  border-color: #f56c6c;
}

.el-form-item {
  margin-bottom: 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}
</style>